﻿using Unity.Burst;
using Unity.Collections;
using Unity.Entities;
using Unity.Jobs;
using Unity.Mathematics;
using Unity.Transforms;
using UnityEngine;

public class MinoInstructionSystem : SystemBase {
    public Entity gameEntity;

    protected override void OnUpdate() {
        if (!EntityManager.Exists(gameEntity)) {
            return;
        }
        float deltaTime = Time.DeltaTime;
        float interval = 0.5f;
        var autoMoveTimeStamp = EntityManager.GetComponentData<AutoMoveTimeStamp>(gameEntity);
        var istQueue = EntityManager.GetBuffer<MinoInstraction>(gameEntity);

        if (Input.GetKeyDown(KeyCode.UpArrow)) {
            istQueue.Add(new MinoInstraction { Value = InstractionType.Rotate });
        } else if (Input.GetKeyDown(KeyCode.LeftArrow)) {
            istQueue.Add(new MinoInstraction { Value = InstractionType.Left });
        } else if (Input.GetKeyDown(KeyCode.RightArrow)) {
            istQueue.Add(new MinoInstraction { Value = InstractionType.Right });
        } else if (Input.GetKeyDown(KeyCode.DownArrow)) {
            istQueue.Add(new MinoInstraction { Value = InstractionType.Down });
            autoMoveTimeStamp.Value = interval;
        } else if (Input.GetKeyDown(KeyCode.Space)) {
            istQueue.Add(new MinoInstraction { Value = InstractionType.Fall });
            autoMoveTimeStamp.Value = interval;
        }

        autoMoveTimeStamp.Value -= deltaTime;
        if (autoMoveTimeStamp.Value < 0f) {
            istQueue.Add(new MinoInstraction { Value = InstractionType.AutoMove });
            autoMoveTimeStamp.Value = interval;
        }

        EntityManager.SetComponentData(gameEntity, autoMoveTimeStamp);
    }
}
